package view.audit
{
	import business.AvatarDelegate;
	import business.BookDelegate;
	import business.CardDelegate;
	import business.GameDelegate;
	import business.UserDelegate;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.system.System;
	
	import model.AppCons;
	import model.ModelLocator;
	
	import mx.collections.ArrayCollection;
	import mx.containers.HBox;
	import mx.containers.VBox;
	import mx.controls.Alert;
	import mx.controls.Button;
	import mx.controls.CheckBox;
	import mx.controls.ComboBox;
	import mx.controls.DataGrid;
	import mx.controls.Label;
	import mx.controls.LinkButton;
	import mx.controls.SWFLoader;
	import mx.controls.TextArea;
	import mx.controls.TextInput;
	import mx.core.Application;
	import mx.events.CloseEvent;
	import mx.events.FlexEvent;
	import mx.rpc.Fault;
	import mx.rpc.events.FaultEvent;
	import mx.utils.StringUtil;
	
	import util.GCUtil;
	import util.LogUtil;
		
	[Bindable]
	public class AuditClass extends VBox
	{
		//public var contentTypesSrc:XML;
		//public var contentTypes:XMLListCollection;
		
		public var m_items:ArrayCollection;
		
		public var page:int;
		public var pagecnt:int;
		public var pageVolume:int;
		public var pageIndices:Array;
			
		public var cmEditorType:ComboBox;
		
		private var selectedIndex:int;
//		public var loaderLock:Boolean;
		
		public var index:int;
				
		protected var delegateBook:BookDelegate;
		protected var delegateCard:CardDelegate;
		private var delegateUser:UserDelegate;
		private var delegateAvatar:AvatarDelegate;
		
		private var type:String;	//产品类型

		private var bInSearch:Boolean;		//是否在搜索
		private var searchPattern:String;	//搜索关键字
		private var searchType:String;		//在哪个字段搜索
		
		private var range:String;	//列表范围：审核，未审核，全部
		private var latestMode:String = '0';		
		
		//界面元件
		public var item_id:TextInput;
		public var item_bid:TextInput;
		public var item_aid:TextInput;
		public var item_avatar:TextInput;
		public var item_sid:TextInput;
		public var item_mode_label:Label;
		public var item_mode:ComboBox;
		public var item_title:TextInput;
		
		public var item_catalog:TextInput;
		public var item_saveTime:TextInput;
		public var item_fileSize:TextInput;
		public var item_totalTime:TextInput;
		public var item_click:TextInput;
		public var item_flower:TextInput;
		public var item_favorite:TextInput;
		public var item_comment:TextInput;
		public var item_gameid:TextInput;
		public var item_game:TextInput;
		public var item_guildid:TextInput;
		public var item_tag:TextInput;
		public var item_adwords:Object;
		public var item_editorWords:Object;
		public var item_sendMsg:Object;
		
		public var item_label_reaudit:Label;
		public var item_audit:CheckBox;
		public var item_share:CheckBox;
		public var item_class:CheckBox;
		public var item_zhuanqu:CheckBox;
		public var item_delete:CheckBox;
		public var item_eventId:TextInput;
		public var item_spread:CheckBox;
		public var item_backTogame7:Button;	
		
		public var item_player:SWFLoader;
		public var item_playerBox:VBox;
		public var item_player_hbox:HBox;
		public var item_box:HBox;
		public var commonWords:ComboBox;
		public var videoBox:HBox;
		
		public var myGrid:DataGrid;
		
		//public var localCon:LocalConnection;
		
		public var subsText:TextArea;
		public var firstTimeLoad:Boolean = true;
		private var logId:String = '-1';
		
		public const UNAUDIT:int = 1;
		public const AUDITED:int = 2;
		public const ALL:int = 3;
		public const CLASSIC:int = 4;
		public const DELETED:int = 5;
		
		private var showAssetType:int = ALL;	
		
		private var playerPools:Array = new Array;
		
		public function AuditClass()
		{
        	this.delegateBook = new BookDelegate(this);
			this.delegateCard = new CardDelegate(this);
			this.delegateUser = new UserDelegate(this);
			this.delegateAvatar = new AvatarDelegate(this);
			
			this.type = "card";
			this.range = "unaudit";

			this.page = 0;
			this.index = 0;
			
			getPage(this.page);
			
			this.bInSearch = false;
			
			this.selectedIndex = -1;
			
			/* localCon = new LocalConnection();
			localCon.addEventListener(StatusEvent.STATUS, onStatus); */

//			this.loaderLock = false;
//			
//			this.conn = new LocalConnection();
//			conn.connect('test');
//			conn.client = this;
		}
		
        /* private function onStatus(event:StatusEvent):void {
            switch (event.level) {
                case "status":
                    trace("LocalConnection.send() succeeded");
                    break;
                case "error":
                    trace("LocalConnection.send() failed");
                    callLater( refleshWhenError );
                    break;
            }
        }
        
        private function refleshWhenError():void
        {
        	trace( ' !!!!!!!!!!!!! ' );
        	localCon.send("Player_swf","closeLocalcon");
         	item_player = null;
            //refleshCurrentWork( null );       	
        } */
        
		public function onDataGridItemClick(isForce:Boolean=false, reflesh:Boolean=false):void
		{
			if(myGrid.selectedItem==null)return;
			if( !myGrid.selectedItem.deleteCheck )
			{
				item_audit.selected = true;
			}

if (myGrid.selectedItem.share > 0)
	item_share.selected = true;

			item_zhuanqu.selected = true;
			
			if (myGrid.selectedItem == null )	
			{
				return;
			}
			
			if ( myGrid.selectedIndex == this.selectedIndex && !reflesh )
				return;
			
			this.selectedIndex = myGrid.selectedIndex;
			this.commonWords.selectedIndex = 0;
			
			if (myGrid.selectedItem.audit == 100)
				item_label_reaudit.visible = true;	
			else
				item_label_reaudit.visible = false;
			
			item_box.enabled = true;
			
			item_sendMsg.text = '';
						
			var datass:Object = this.myGrid.selectedItem;
			var isDiffMode:Boolean = isForce;
			
			//连环画   new新的
			if(this.type == 'book')
			{
				if( item_player && item_player.source && String(item_player.source).indexOf('bookplayerforbackadmin.swf') < 0 )
				{
					isDiffMode = true;
				}
				
				latestMode = '-1';
			}
			else if(this.myGrid.selectedItem.mode)
			{
				if(this.myGrid.selectedItem.mode != latestMode) 
				{
					latestMode = this.myGrid.selectedItem.mode;	
					isDiffMode = true;
				}
			}
			
			if (item_player)
			{
				if( item_player.source )
				{
					//Object(item_player.content).application.player.myBar.connectLocal();
					//localCon.send("Player_swf","playerStop");
					try
					{
						if(Object(item_player.content).application && Object(item_player.content).application.player)
							Object(item_player.content).application.player.stopPlay();
					}
					catch( e:Error )
					{
						trace( e.getStackTrace() );
					}
				}
			}
			else
			{
				isDiffMode = true;
			}
			
			Application.application.parameters.info = myGrid.selectedItem.flashVars;

			if(isDiffMode)
			{
				if( item_playerBox.numChildren > 0 )
				{
					//delPlayerFormPools( latestMode );
					//item_playerBox.removeAllChildren();
					GCUtil.runGc();
				}
				
				var player:SWFLoader = getPlayerInPools( latestMode );
				
				item_player = null;
				
				item_playerBox.removeAllChildren();
				
				if( player && !isForce )
				{
					item_player = player;
					Object(item_player.content).application.model.refleshParameters();
				}		
				else
				{	
					delPlayerFormPools( latestMode );
						
					item_player = new SWFLoader();
					
					item_player.width = 635;
					item_player.height = 500;	
									
					item_player.id = "item_player";
					item_player.autoLoad = false;
					item_player.scaleContent = true;
		
					item_player.source = this.myGrid.selectedItem.player;
					
					item_player.load();
					item_player.addEventListener(Event.INIT,playerInit);
					
					addPlayerPool( item_player, latestMode );
					
				}
				if(item_player)
					item_playerBox.addChild(item_player);
				
				firstTimeLoad = false;
			}
			else
			{
				if(firstTimeLoad)
				{
					if(latestMode == '-1')
					{
						item_player.source = "http://www1.aipai.com/app/www/player/bookplayerforbackadmin.swf";
					}
					else
					{
						item_player.source = "http://www1.aipai.com/app/www/player/babycardplayer.swf";
//						item_player.source = "D:/space/flexspace/babycardplayer/bin/babycardplayer.swf";
					}
					item_player.autoLoad = true;
					firstTimeLoad = false;
					
					addPlayerPool( item_player, latestMode );
				}
				else if( item_player.source )
				{
					//localCon.send("Player_swf","playNewSource");
					Object(item_player.content).application.model.refleshParameters();
				}
					
			}
			
			//item_player.load();
			item_backTogame7.visible = 1000-int(myGrid.selectedItem.gameid) > 0 && 700-int(myGrid.selectedItem.gameid) < 0;
			item_backTogame7Enable = true;
		}
		
		private function addPlayerPool( player:SWFLoader, mode:String ):void
		{
			if( !playerPools )
			{
				playerPools = new Array();
			}
			playerPools.push( {mode:mode, player:player} );
		}
		
		private function getPlayerInPools( mode:String ):SWFLoader
		{
			if( playerPools )
			{	
				for each( var obj:Object in playerPools )
				{
					if( obj.mode == mode )
					{
						return (obj.player as SWFLoader);
					}
				}
			}
			
			return null; 	
		}
		
		private function delPlayerFormPools( mode:String ):void
		{
			if( playerPools )
			{
				for( var i:int=0; i<playerPools.length; i++ )
				{
					if( playerPools[i].mode == mode )
					{
						var player:SWFLoader = (playerPools[i].player as SWFLoader);
						player.source = '';
						player.load( null );
						playerPools.splice( i, 1 );
						//player.parent.removeChild( player );
						
						return ;
					}
				}
			}
		}        
		
		public function getPage(page:int=0):void
		{
			if (this.bInSearch)
			{
				if (this.type == "book")
					this.delegateBook.getBooksBySearch(this.searchPattern, this.searchType, page, showAssetType);
				else if (this.type == "card")
					this.delegateCard.getCardsBySearch(this.searchPattern, this.searchType, page, showAssetType);				
			}
			else
			{
				if (this.type == "book")
					this.delegateBook.getBooksByAudit(page,this.range);
				else if (this.type == "card")
					this.delegateCard.getCardsByAudit(page,this.range);
			}
			
			if (item_box)
			{
				item_box.enabled = false;
			}
			
			this.selectedIndex = -1;
			
			this.delegateCard.getZoneList(); //获取录像分区数
		}
		
		/**------------------------edit by zhanghm in 2010.07.09 16:19-------------------------------------------------------*/
		public function onGetGameInfo( gameName:String, gameId:String ):void{
			if(gameName != ""){
				onGetGameId( gameName );
			}
			else if(gameId != ""){
				onGetGameName( gameId );
			}
		}
		
		public function onGetGameName( gameId:String ):void{
			var gameDelegate:GameDelegate = new GameDelegate( this );
			gameDelegate.getNameByGameId( gameId );
		}
		
		public function getNameByGameIdResult(result:Object, token:Object = null):void
		{
			
			var ret:Object = result.result;
			if( ret.code == 0 )
			{
				if( !ret.name )
				{
					Alert.show('没有找到这个游戏名称');
					return ;
				}
				item_game.text = ret.name;
			}
		}
		/**------------------------edit by zhanghm in 2010.07.09 16:19-------------------------------------------------------*/
		public function onGetGameId( gameName:String ):void
		{
			var gameDelegate:GameDelegate = new GameDelegate( this );
			gameDelegate.getIdByGameName( gameName );
		}
		
		public function getIdByGameNameResult(result:Object, token:Object = null):void
		{
			var ret:Object = result.result;
			if( ret.code == 0 )
			{
				if( !ret.gid )
				{
					Alert.show('没有找到这个游戏ID');
					return ;
				}
				item_gameid.text = ret.gid;
			}
		}
		
		private function updateItem(ids:Array,update:Object):void
		{
			if (this.type == "book")
			{
				//LogUtil.getInstance().addEventListener(MyLogEvent.LOGREADY, goUpdateBook);
			  	this.delegateBook.updateBook(ids,update);
			  	LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.AUDIT, LogUtil.UPDATE, {ids:ids,update:update}, ids.toString(),'1', true);
			}
			else if (this.type == "card")
			{
				this.delegateCard.updateCard(ids,update);	
				LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.AUDIT, LogUtil.UPDATE, {ids:ids,update:update}, ids.toString(), '2', true);
			}
		}
		
		/* private function goUpdateBook(event:MyLogEvent):void
		{
			event.target.removeEventListener(MyLogEvent.LOGREADY, goUpdateBook);
			this.logId = event.logId;
			delegateBook.updateBook(event.record.ids, event.record.update);			
		} */

		private function removeItem(page:int,ids:Array):void
		{
			if (this.type == "book")
			{
			  	this.delegateBook.removeBooks(page,ids);
			  	LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.AUDIT, LogUtil.DEL, {ids:ids,page:page}, ids.toString(), '1', true);
			}
			else if (this.type == "card")
			{
				this.delegateCard.removeCards(page,ids);
				LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.AUDIT, LogUtil.DEL, {ids:ids,page:page}, ids.toString(), '2', true);
			}
				
		}

		private function getItemById(ids:Array):void
		{
			if (this.type == "book")
			  	this.delegateBook.getBooksById(ids);
			else if (this.type == "card")
				this.delegateCard.getCardsById(ids);		
		}		
				
		private function refreshPage(result:Object):void
		{
			result = result.result;

			this.page = result.page>0?result.page:0;
			this.pagecnt = result.pagecnt>1?result.pagecnt:1;
			
			this.makePageIndices();

			if (this.type == "book")
			{
			  	this.itemsPrepare(result.books);
			  	item_mode_label.visible = false;
			  	item_mode.visible = false;
			}
			else if (this.type == "card")
			{
				this.itemsPrepare(result.cards);
				item_mode_label.visible = true;
				item_mode.visible = true;
			}				
		}
		
		private function setUploadType(arr:Array):void
		{
			if(arr==null || arr.length==0)return;
			for(var i:int=0; i<arr.length; i++)
			{
				if(arr[i].guildid=="0")
					arr[i]["guildname"] = "宝宝上传";
				else if(arr[i].guildid=="1" || arr[i].guildid=="2")
					arr[i]["guildname"] = "网页上传";
//				else if(arr[i].guildid=="2")
//					arr[i]["guildname"] = "网页上传,FLV拷贝";
				else if(arr[i].guildid=="3")
					arr[i]["guildname"] = "远程中转上传";
				
			}
		}
		
		public function itemsPrepare(items:Array,method:String = "get"):void
		{
			//预处理结果集
			if (method == "get")
			{
				setUploadType(items);
				
				this.m_items = new ArrayCollection(items);
			}
			else if (method == "update")
			{
				var newItems:ArrayCollection = new ArrayCollection(items);
				
				for each ( var item1:Object in newItems )
				{
					for(var i:int=0;i<this.m_items.length;++i)
					{
						if (this.m_items[i].id == item1.id)
						{
							this.m_items[i] = item1;
							break;
						}					
					}										 
				}
				
				item_audit.selected = false;				
			}
			else if (method == "delete")
			{
				for each ( var id:int in items )
				{
					for(var j:int=0;j<this.m_items.length;++j)
					{
						if (this.m_items[j].id == id)
						{
							this.m_items.removeItemAt(j);
							break;
						}					
					}										 
				}
				
				item_audit.selected = false;									
			}
			
			for each ( var item:Object in this.m_items )
			{
				item.oldid = item.id
				
				if (item._class > 0)
					item.classCheck = true;
				else
					item.classCheck = false;
									
				if (item.share > 0)
					item.shareCheck = true;
				else
					item.shareCheck = false;
				
				if (item.audit == 1)
				{
					item.auditCheck = "已通过";
					item.deleteCheck = false;
				}
				else if(item.audit == 0)
				{
					item.auditCheck = "未审核";
					item.deleteCheck = false;					
				}
				else if (item.audit == '-1')
				{
					item.auditCheck = "未通过";
					item.deleteCheck = true;
				}
					
				item.catalogName = AppCons.getCatalogNameById( int(item.catalog) ) + '('+item.catalog+')';	
								
				//if (item.contract == 1)
				//	item.contractCheck = true;
				//else
				//	item.contractCheck = false;														
			}
			
		}
		
		public function updatePrepare():Object
		{
			if (myGrid.selectedItem == null)	
			{
				return null;
			}
			var update:Object = new Object();
						
			if(myGrid.selectedItem.id != item_id.text)
			{
				update.id = item_id.text;
				
				//如果更改了ID，需要同步修改
				//myGrid.selectedItem.oldid = item_id.text;
				myGrid.selectedItem.id = item_id.text;
			}
				
			if(myGrid.selectedItem.bid != item_bid.text)
				update.bid = item_bid.text;
				
			if(myGrid.selectedItem.aid != item_aid.text)
				update.aid = item_aid.text;
				
			//if(myGrid.selectedItem.avatar != item_avatar.text)
			//	update.avatar = item_avatar.text;
				
			if(myGrid.selectedItem.sid != item_sid.text)
				update.sid = item_sid.text;
			
			if(item_mode.visible && myGrid.selectedItem.mode != item_mode.selectedIndex)
				update.mode = item_mode.selectedIndex;				
			
			if(myGrid.selectedItem.title != item_title.text)
				update.title = item_title.text;
				
			if(myGrid.selectedItem.catalog != item_catalog.text)
				update.catalog = item_catalog.text;
			
			if(myGrid.selectedItem.saveTime != item_saveTime.text)
				update.saveTime = item_saveTime.text;
			
			if(myGrid.selectedItem.fileSize != item_fileSize.text)
				update.fileSize = item_fileSize.text;
			
			if(myGrid.selectedItem.totalTime != item_totalTime.text)
				update.totalTime = item_totalTime.text;
			
			if(myGrid.selectedItem.click != item_click.text)
				update.click = item_click.text;

			if(myGrid.selectedItem.flower != item_flower.text)
				update.flower = item_flower.text;
				
			if(myGrid.selectedItem.favorite != item_favorite.text)
				update.favorite = item_favorite.text;
				
			if(myGrid.selectedItem.comment != item_comment.text)
				update.comment = item_comment.text;																																			

			if(myGrid.selectedItem.gameid != item_gameid.text)
				update.gameid = item_gameid.text;	
				
			if(myGrid.selectedItem.game != item_game.text)
				update.game = item_game.text;	
				
			//if(myGrid.selectedItem.guildid != item_guildid.text)
			//	update.guildid = item_guildid.text;	
				
			if(myGrid.selectedItem.tag != item_tag.text)
				update.tag = item_tag.text;	
				
			if(myGrid.selectedItem.adwords != item_adwords.text)
				update.adwords = item_adwords.text;	

			if(myGrid.selectedItem.editorWords != item_editorWords.text)
				update.editorWords = item_editorWords.text;	
								
			if(item_sendMsg.text != "")
				update.sendMsg = item_sendMsg.text;	
				
			if (item_delete.selected)
			{
				//64位 32位兼容问题，这里使用一个正数
				update.audit = 111;	
			}				
			else if (myGrid.selectedItem.auditCheck != item_audit.selected)
			{
				if (item_audit.selected)
					update.audit = 1;
				else
					update.audit = 0;
			}
			
			if (myGrid.selectedItem.shareCheck != item_share.selected)
			{
				if (item_share.selected)
					update.share = 1;
				else
					update.share = 0;
			}
			else if(item_share.selected)
			{
				update.share = 1;
			}
			else if(item_share.selected==false)
			{
				update.share = 0;
			}
																											
			if (myGrid.selectedItem.classCheck != item_class.selected)
			{
				if (item_class.selected)
					update._class = 1;
				else
					update._class = 0;
			}

			if (item_zhuanqu.selected)
				update.zhuanqu = 1;
			else
				update.zhuanqu = 0;
			
			if(item_spread.selected)
				update.spread = 1;
			else 
				update.spread = 0;
				
			if(myGrid.selectedItem.eventId != item_eventId.text)
				update.eventId = item_eventId.text;					
											
			return update;
		}
		
		public function onSubmit():void
		{	
			if (myGrid.selectedItem == null)	
			{
				Alert.show("请先选择要审核的作品");
				return;
			}
						
			//处理删除
			if (item_delete.selected)
			{	
				//Alert.show(myGrid.selectedItem.audit);
				
 				Alert.yesLabel = '确定';
				Alert.noLabel = '取消';
				Alert.buttonWidth = 50;
				Alert.buttonHeight = 20;
	
				Alert.show('确定删除吗？',
					'提示',Alert.YES | Alert.NO,null,onDelConfirmed,null,Alert.NO);
				
				return;					
			}
					
			//处理update					
			var update:Object = this.updatePrepare();
            
            if (update == null)
            	return;
            	
            var ids:Array = new Array();
            ids.push(myGrid.selectedItem.oldid);
            
            updateItem(ids,update)
		}

        private function onDelConfirmed(event:CloseEvent):void 
        {
            if (event.detail==Alert.YES)
            { 
            	/*  
            	var ids:Array = new Array();
            	ids.push(myGrid.selectedItem.id);
            	
            	removeItem(this.page,ids);
            	*/
            	
				var update:Object = this.updatePrepare();
	            
	            if (update == null)
	            	return;
	            	
	            var ids:Array = new Array();
	            ids.push(myGrid.selectedItem.oldid);
	            
	            updateItem(ids,update)            		       		
            }	
        }
        		
		public function playerInit(evt:Event):void
		{
			evt.target.content.addEventListener(FlexEvent.APPLICATION_COMPLETE,appOk, true);
		}
		
		public function appOk(evt:Event):void
		{
			evt.target.addEventListener("subsLoaded",subsLoadedEvt);
		}
		
		public function subsLoadedEvt(evt:Event):void
		{
			var data:*;
			var effectData:*;
			
			if(this.type == 'book')
			{
				data = evt.target.model.pagesInfo
			}
			else
			{
				data = evt.target.model.subs;
				effectData = evt.target.model.effectTexts;
			}
			
			showSubs(data);
			showEffectTexts(effectData);
		}

		public function showSubs(xmlListCol:*):void
		{
			var text:String = "<b>字 幕</b>：(出现时间)\n";
			if(this.type == 'book')
			{
				for ( var i:int = 0; i < xmlListCol.page.length(); ++i )        
	            {
	            	text += "<b>"+xmlListCol.page[i].@realText+"</b>  (第"+ int(i+1) + "图)\n";
	            }				
			}
			else
			{
				for each ( var sub:XML in xmlListCol )
				{
					var str:String = unescape(sub.@text);
					var myPattern:RegExp = /\scolor=\S*\s/gi;  
					str = str.replace(myPattern, " color='#333333' ");  
					var sizePattern:RegExp = /\ssize=\S*\s/gi; 
					str = str.replace(sizePattern, " size='14' ");
						
					text += str +"  ("+ int(sub.@time) + "--" + (int(sub.@time)+int(sub.@stay))  +")\n";	
				}
			}
			
			subsText.htmlText = text;
		}

		
		public function showEffectTexts(xmlListCol:*):void
		{
			var text:String = "\n\n <b>特效字幕</b>：\n";
			
			for each ( var effectText:XML in xmlListCol )
			{
				text += "<b>"+effectText.@text+"</b> \n";	
			}
			
			subsText.htmlText += text;
		}			
		
//		public function unlock():void
//		{
//			this.loaderLock = false;
//		}
		
		public function getBooksForAuditResult(result:Object, token:Object = null):void
		{
			this.refreshPage(result);
		}

		public function getBooksBySearchResult(result:Object, token:Object = null):void
		{
			this.refreshPage(result);
		}
				
		public function getBooksByIdResult(result:Object, token:Object = null):void
		{
			this.refreshPage(result);
		}
		
		public function removeBooksResult(result:Object, token:Object = null):void
		{
			//Alert.show("删除成功");
			//refreshPage(result);
			result = result.result;
			this.itemsPrepare(result.ids,"delete");					
		}	
		
		public function updateBookResult(result:Object, token:Object = null):void
		{
			result = result.result;
			this.itemsPrepare(result.books,"update");
		}

		public function getCardsForAuditResult(result:Object, token:Object = null):void
		{
			this.refreshPage(result);
		}
		
		public function getCardsBySearchResult(result:Object, token:Object = null):void
		{
			this.refreshPage(result);
			
			
		}
				
		public function getCardsByIdResult(result:Object, token:Object = null):void
		{
			this.refreshPage(result);
		}
		
		public function removeCardsResult(result:Object, token:Object = null):void
		{
			result = result.result;
			this.itemsPrepare(result.ids,"delete");					
		}	
		
		public function updateCardResult(result:Object, token:Object = null):void
		{
			result = result.result;
			this.itemsPrepare(result.cards,"update");
		}

	 	public function onRefreshClick():void
	 	{
	 		this.bInSearch = false;
	 		getPage();	
	 	}	
	 					
		public function onTypeClick(type:String):void
		{
			this.bInSearch = false;
			
			this.type = type;
			this.getPage();		
			firstTimeLoad = true;		
		}
		
		public function onRangeClick(method:String, showAssetType:int=UNAUDIT):void
		{
			this.bInSearch = false;
			this.showAssetType = showAssetType;
			this.range = method;
			this.getPage();
		}
		
		public function onBtnPreviewClick():void
		{
			this.verticalScrollPosition = item_player_hbox.y;
		}
		
		public function onBtnStopClick():void
		{
			//if (localCon)
			//	localCon.send("Player_swf","playerStop");
			try
			{
				Object(item_player.content).application.player.stopPlay();
			}
			catch( e:Error )
			{
				trace( e.getStackTrace() );
			}
		}
		
		public function onBtnBackClick():void
		{
			this.verticalScrollPosition = 0;
			
			invalidateProperties();
		}
				
		public function onSearch(type:int,pattern:String):void
		{
			if (pattern.length <= 0)
				return;
			
			this.searchPattern = StringUtil.trim(pattern);
		
			if (type == 0)
			{
				this.searchType = 'id';
			}
			else if (type == 1)
			{
				this.searchType = 'bid';
			}
			else if (type == 2)
			{
				this.searchType = 'aid';
			}
			else if (type == 3)
			{
				this.searchType = 'title';
			}
			else if (type == 4)
			{
				this.searchType = 'avatar';
			}
			else if (type == 5)
			{
				this.searchType = 'gameid';
			}
			else if (type == 6)
			{
				this.searchType = 'guildid';
			}
															            
            this.bInSearch = true;
            
            getPage(0);
		}		
		
		public function goto(evt:MouseEvent):void
		{
			if(range == "all" && evt.currentTarget.label == "尾页")
			{
				// 数据量太大 ，这种情况暂时不查询				
				return ;
			}
			var page:int = LinkButton(evt.currentTarget).data.page;
			getPage(page);
		}
		
		public function gotoPage(page:String):void
		{
			if (page.length>0)
			{
				getPage(int(page)-1);
			}
		}
				
		private function makePageIndices():void
		{
			var a:Array = new Array();
			a.push({page:0,desc:'首页'});			
			a.push({page:page-1,desc:'前一页'});			
			a.push({page:page+1,desc:'后一页'});
			a.push({page:pagecnt-1,desc:'尾页'});
			this.pageIndices = a;
		} 
		
		
	 	public function onLabelPlayPageClick():void
	 	{
	 		var u:URLRequest = new URLRequest(myGrid.selectedItem.url); 
	 		navigateToURL(u,"_blank"); 
	 	}
	 	
        public function onLabelCopyUrlClick():void
        {
        	System.setClipboard(myGrid.selectedItem.url);
        }
        	 	
	 	public function onUserPicClick():void
	 	{
	 		var u:URLRequest = new URLRequest(myGrid.selectedItem.userUrl); 
	 		navigateToURL(u,"_blank"); 	 		
	 	}

	 	public function onAvatarPicClick():void
	 	{
	 		var u:URLRequest = new URLRequest(myGrid.selectedItem.avatarUrl); 
	 		navigateToURL(u,"_blank"); 	 		
	 	}
	 		 	 		
		public function fault(error:FaultEvent,token:Object = null):void
		{
			Alert.show(error.fault.faultString,'error');
		}
		
		public function onPlayerError():void
		{
			Alert.show("io error");	
		}
		
		public function onItemAuditClick():void
		{
			if 	(item_audit.selected && item_delete.selected)
				item_delete.selected = false;	
		}

		public function onItemDeleteClick():void
		{
			if 	(item_delete.selected && item_audit.selected)
				item_audit.selected = false;	
		}
		
		public function onBtnClearUserClick():void
		{
			//处理删除
 			Alert.yesLabel = '确定';
			Alert.noLabel = '取消';
			Alert.buttonWidth = 50;
			Alert.buttonHeight = 20;

			Alert.show('“清除”操作会重置用户头像，确定吗？',
				'提示',Alert.YES | Alert.NO,null,onClearUserConfirmed,null,Alert.NO);
			
			return;					
		}
		
        private function onClearUserConfirmed(event:CloseEvent):void 
        {
            if (event.detail==Alert.YES)
            {  
            	LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.AUDIT, LogUtil.UPDATE, String(myGrid.selectedItem.bid), '', '', true); 
            	this.delegateUser.clearPic(myGrid.selectedItem.bid);	       		
            }	
        }
        
		public function clearPicUserResult(result:Object, token:Object = null):void
		{
			//				
		}
		        		
		public function onBtnClearAvatarClick():void
		{
			//处理删除	
 			Alert.yesLabel = '确定';
			Alert.noLabel = '取消';
			Alert.buttonWidth = 50;
			Alert.buttonHeight = 20;

			Alert.show('“清除”操作会重置角色头像，确定吗？',
				'提示',Alert.YES | Alert.NO,null,onClearAvatarConfirmed,null,Alert.NO);
			
			return;								
		}
		
        private function onClearAvatarConfirmed(event:CloseEvent):void 
        {
            if (event.detail==Alert.YES)
            { 
            	LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.AUDIT, LogUtil.UPDATE, String(myGrid.selectedItem.aid), '', '', true);  
            	this.delegateAvatar.clearPic(myGrid.selectedItem.aid);	       		
            }	
        }
        
		public function clearPicAvatarResult(result:Object, token:Object = null):void
		{
			//				
		}
		
		public function getNext(event:MouseEvent, isForce:Boolean=false):void
		{
			if(myGrid.selectedIndex == m_items.length - 1)
			{
				onBtnBackClick();
				return ;
			}			
			
			myGrid.selectedIndex++;
			onDataGridItemClick(isForce);
		}
		
		public function refleshCurrentWork(event:Event):void
		{
			onDataGridItemClick(true, true);
		}
		
		public function getPrev(event:MouseEvent, isForce:Boolean=false):void
		{
			if(myGrid.selectedIndex == 0)
			{
				onBtnBackClick();
				return ;
			}
			myGrid.selectedIndex--;
			onDataGridItemClick(isForce);
		}		
		
		public function getZoneListResult(result:Object, token:Object = null):void
		{
			if(result.result==null)
				return;
			result = result.result;
			var length:int = int(result.num);
			trace(length);
			var btn:Button ; 
			videoBox.data = length;
			videoBox.removeAllChildren();
			for(var i:int=0; i<length; i++)
			{
				btn = new Button();
				btn.label = "录像" + (i+1);
				btn.data = i;
				videoBox.addChild(btn);
				btn.setStyle("textRollOverColor",0xFF0000);
				btn.addEventListener(MouseEvent.CLICK,onVideoClickHandler);
				
			}
		}
		
		private function onVideoClickHandler(event:MouseEvent):void
		{
			var num:int = event.currentTarget.data;
			changeBtnColor(num);
			this.delegateCard.getCardByZone(int(videoBox.data), num);
		}
		
		/**  改变选中按钮颜色 **/
		private function changeBtnColor(id:int):void
		{
			var length:int = videoBox.numChildren;
			var btn:Button;
			for(var i:int=0; i<length; i++)
			{
				btn = videoBox.getChildAt(i) as Button;
				if(id==btn.data)
					btn.setStyle("color", 0xFF0000);
				else
					btn.setStyle("color", 0x000000);
			}
		}
		
		public function getCardByZoneResult(result:Object, token:Object = null):void
		{
			result = result.result;
			itemsPrepare(result.data as Array,"get")
		}
		
		public function updateZoneResult(result:Object, token:Object = null):void
		{
			result = result.result;
			if(result.code==0)
			{
				Alert.show("分区完成！");				
			}
			else
			{
				Alert.show("分区失败！");	
			}
		}
		public function backToQiquResult(result:Object, token:Object = null):void
		{
			result = result.result;
			if(result.code)
			{
				var fault:Fault = new Fault('',result.msg);
				var error:FaultEvent = new FaultEvent('fault',false,true,fault);
				this.fault(error);
				return;				
			}
			else
			{
				item_backTogame7Enable = false;
			}
		}
		
		public var item_backTogame7Enable:Boolean = false;
		public function item_backTogame7_clickHandler(event:MouseEvent):void
		{
			switch(type)
			{
				case "card":
					delegateCard.backToQiqu( myGrid.selectedItem.id );
					break;
				case "book":
					delegateBook.backToQiqu( myGrid.selectedItem.id );
					break;
			}
		}
		
		
	}	
	
}
